package com.goodfox.web.generic.login.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.goodfox.web.generic.account.mapper.AccountMapper;
import com.goodfox.web.generic.login.entity.LoginLog;
import com.goodfox.web.generic.login.mapper.LoginLogMapper;
import com.goodfox.web.generic.login.service.LoginService;
import com.goodfox.web.generic.provide.annotation.NoteExplain;

/**
 * 登录Service实现类
 * @author qin gt
 *
 */
@Transactional
@Service(value="loginService")
@NoteExplain(comment="系统登录")
public class LoginServiceImpl implements LoginService {

	/** log4j日志器 */
	private Logger logger=Logger.getLogger(LoginServiceImpl.class);

	/** 登录Mapper */
	@Autowired
	private LoginLogMapper loginLogMapper;

	/** 账号Mapper */
	@Autowired
	private AccountMapper accountMapper;

	@NoteExplain(comment="登录成功")
	public String loginSuccess(LoginLog loginLog){
		loginLog.setLgnResult("1");
		loginLog.setLgnTime(new Date());
		loginLogMapper.insertLoginlog(loginLog);
		
		//将本次登录时间作为上次登出时间（用户未使用正常的登出功能）
		Map map=new HashMap();
		map.put("lgnLogId", loginLog.getLgnLogId());
		map.put("actId", loginLog.getActId());
		LoginLog lastLog=loginLogMapper.selectLastLoginLog(map);
		if(lastLog!=null && lastLog.getLgtTime()==null){
			LoginLog logoutLog=new LoginLog();
			logoutLog.setLgnLogId(lastLog.getLgnLogId());
			logoutLog.setLgtTime(new Date());
			loginLogMapper.updateLogoutlog(logoutLog);
		}
		return loginLog.getLgnLogId();
	}

	@NoteExplain(comment="登录失败")
	public void loginFailure(LoginLog loginLog){
		loginLog.setLgnResult("0");
		loginLog.setLgnTime(new Date());
		loginLogMapper.insertLoginlog(loginLog);
	}
	
	@NoteExplain(comment="登录账号检查")
	public String checkLoginAccount(String actName){
		return accountMapper.selectActIdByName(actName);
	}

	@NoteExplain(comment="登出成功")
	public void logoutSuccess(Map map){
		LoginLog lastLog=loginLogMapper.selectLastLoginLog(map);
		lastLog.setLgtTime(new Date());
		loginLogMapper.updateLogoutlog(lastLog);
	}
	
}
